﻿using BCCommon;
using BCCommon.Enums;
using BCCommon.TMS.Order;
using BCData.TMS.Driver;
using BCData.TMS.NotificationMessageRecord;
using BCData.TMS.Order.Order;
using BCData.TMS.Order.OrderCancelRecord;
using BCData.TMS.Order.OrderExtention;
using BCData.TMS.Order.OrderPool;
using BCDto.Sim.Admin.Admin;
using BCDto.TMS.Order.OrderCancelRecord;
using BCDto.TMS.Order.OrderExtention;
using BCEntity.Common.EntityNameConst;
using BCEntity.TMS.NotificationMessageRecord;
using BCEntity.TMS.Order.Order;
using BCEntity.TMS.Order.OrderCancelRecord;
using BCService.Common.PushMessage.PushMessageSend;
using BCService.Common.RedisClear;
using BCService.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCService.TMS.Order.OrderCancelRecord
{
    public class OrderCancelRecordService : IOrderCancelRecordService
    {
        private readonly IOrderCancelRecordData orderCancelRecordData;
        private readonly IOrderPoolData orderPoolData;
        private readonly IOrderData orderData;
        private readonly IOrderExtentionData orderExtentionData;
        private readonly INotificationMessageRecordData notificationMessageRecordData;
        //private readonly IVehicleTransportRecordData vehicleTransportRecordData;
        private readonly IPushMessageSendService pushMessageSendService;
        private readonly IRedisClearService redisClearService;
        private readonly IRedisService redisService;
        private readonly IDriverData driverData;

        public OrderCancelRecordService(IOrderCancelRecordData orderCancelRecordData,
            IOrderPoolData orderPoolData,
            IOrderData orderData,
            IOrderExtentionData orderExtentionData,
            INotificationMessageRecordData notificationMessageRecordData,
            //IVehicleTransportRecordData vehicleTransportRecordData,
            IPushMessageSendService pushMessageSendService,
            IRedisClearService redisClearService,
            IRedisService redisService,
            IDriverData driverData)
        {
            this.orderCancelRecordData = orderCancelRecordData;
            this.orderPoolData = orderPoolData;
            this.orderData = orderData;
            this.orderExtentionData = orderExtentionData;
            this.notificationMessageRecordData = notificationMessageRecordData;
            //this.vehicleTransportRecordData = vehicleTransportRecordData;
            this.pushMessageSendService = pushMessageSendService;
            this.redisClearService = redisClearService;
            this.redisService = redisService;
            this.driverData = driverData;
        }

        public OrderCancelRecordDto Add(long orderId, bool isDriverCancel, string cancelOrderPromising, string driverName)
        {
            var orderDto = this.orderData.GetEntity(orderId).GetAwaiter().GetResult();
            //当车辆信息为空时，代表是用户取消订单。
            if (isDriverCancel)
            {
                //TODO:用户取消订单和司机取消订单，都需要通知管理中心和物流部
                

                //this.notificationMessageRecordData.InsertAllAsync(adminBelongAreaList.Select(item => new NotificationMessageRecordEntity
                //{
                //    NotificationTitle = string.Format("司机已取消订单，司机姓名：{0},车牌号：{1},订单编号：{2}", driverName, orderDto.VehicleNo, orderDto.OrderNo),
                //    NotificationType = NotificationMessageRecordType.DriverCancelOrder.ToString(),
                //    RelatedRecordId = orderDto.OrderId,
                //    AdminId = item.AdminId
                //})).Wait();
            }
            else
            {
                //TODO:用户取消订单和司机取消订单，都需要通知代理商

                //this.notificationMessageRecordData.InsertAllAsync(adminBelongAreaList.Select(item => new NotificationMessageRecordEntity
                //{
                //    NotificationTitle = string.Format("用户已取消订单，订单编号：{0}", orderDto.OrderNo),
                //    NotificationType = NotificationMessageRecordType.UserCancelOrder.ToString(),
                //    RelatedRecordId = orderDto.OrderId,
                //    AdminId = item.AdminId
                //})).Wait();

                //用户取消订单
                ClientCancelOrder(orderDto);
            }
            var entity = new OrderCancelRecordEntity();
            entity.OrderId = orderId;
            entity.DriverId = orderDto.DriverId;
            entity.OrderNo = orderDto.OrderNo;
            entity.CancelOrderPromising = cancelOrderPromising;
            entity.CancelOrderPerson = isDriverCancel ? driverName : orderDto.Shipping;
            entity.CancelStatus = isDriverCancel ? OrderValidationStatus.Pending : OrderValidationStatus.Success;
            return this.orderCancelRecordData.Add(entity).GetAwaiter().GetResult().As<OrderCancelRecordDto>();
        }

        private void ClientCancelOrder(OrderEntity order)
        {
            var cancelOrderTask = this.orderData.CancelOrder(order);
            if (order.DriverId.HasValue)
                this.orderPoolData.ClearOrderAssign(order.OrderId);
            else
                this.orderPoolData.UpdateStatusDone(order.OrderId, null);
            //this.orderInfoFeeRecordData.UpdateStatus(order.OrderNo, OrderInfoFeeEndStatus.ReturnSameWay).GetAwaiter().GetResult();
            //var vehicleTransportRecord = this.vehicleTransportRecordData.Get(order.VehicleId, order.OrderNo).GetAwaiter().GetResult();
            //if (vehicleTransportRecord != null)
            //{
            //    this.vehicleTransportRecordData.SetBatchIgnore(vehicleTransportRecord.VehicleTransportBatchId).GetAwaiter().GetResult();
            //    var vehicleCheckResult = this.vehicleTransportRecordData.CheckOrderNotCanceledExists(vehicleTransportRecord.VehicleTransportBatchNo).GetAwaiter().GetResult();
            //    if (vehicleCheckResult == 0)
            //    {
            //        this.vehicleTransportRecordData.UpdateVehicleTransportStatus(vehicleTransportRecord.VehicleTransportRecordId, TransportStatus.Cancel).GetAwaiter().GetResult();
            //        this.vehicleTransportRecordData.UpdateRollbackVehicleTransportCompleteRecordIsLatest(vehicleTransportRecord.VehicleId).GetAwaiter().GetResult();
            //    }
            //}
            this.redisClearService.RemoveOrderCatch(order.OrderId, order.OrderNo);
            if (order.DriverId.HasValue)
                this.pushMessageSendService.PushMessageForOrder(order.OrderId, PushMessageType.UserCancel);
        }

        public OrderCancelRecordDto Get(long orderCancelRecordId)
        {
            return this.orderCancelRecordData.Get(orderCancelRecordId).GetAwaiter().GetResult().As<OrderCancelRecordDto>();
        }

        public PageableList<OrderCancelRecordDto> Query(long? userId, long? agentRecordId, long? driverId, string orderNo, string vehicleNo, string driverName, OrderValidationStatus? cancelStatus, DateTime? start, DateTime? end, bool? ascending, int pageIndex, int pageSize)
        {
            var (list, count) = this.orderCancelRecordData.Query(userId, agentRecordId, driverId, orderNo, vehicleNo, driverName, cancelStatus, start, end, ascending, pageIndex, pageSize).GetAwaiter().GetResult();

            var result = list.As<IEnumerable<OrderCancelRecordDto>>();

            foreach (var item in result)
            {
                var extendionDtos = this.GetOrderExtentionDtos(item.OrderNo);
                if (extendionDtos.Any())
                {
                    var first = extendionDtos.OrderBy(p => p.EndIndex).First();
                    var last = extendionDtos.OrderBy(p => p.EndIndex).Last();

                    item.FromAddress = first.AreaName;
                    item.ToAddress = last.AreaName;
                }
            }

            return new PageableList<OrderCancelRecordDto>
            {
                Items = result,
                Count = count,
                PageIndex = pageIndex,
                PageSize = pageSize
            };

        }

        #region 获取订单扩展信息

        private List<OrderExtentionDto> GetOrderExtentionDtos(string orderNo)
        {
            string key = string.Format("{0}:OrderNo={1}", EntityNameConst.OrderExtentionEntities, orderNo);
            var orderExtentionEntities = this.redisService.TryGet(key, () =>
            {
                var orderExtentions = this.orderExtentionData.GetList(orderNo).GetAwaiter().GetResult();
                var orderExtentionsOrders = orderExtentions.OrderBy(p => p.EndIndex);
                return orderExtentionsOrders.AsEnumerable();
            }, TimeSpan.FromMinutes(10));

            if (orderExtentionEntities == null || !orderExtentionEntities.Any())
            {
                this.redisService.DeleteAsync(key);
            }
            return orderExtentionEntities.As<List<OrderExtentionDto>>();
        }

        #endregion 获取订单扩展信息 

        public OrderCancelRecordDto ValidationFail(AdminDto adminDto, long orderCancelRecordId, OrderCancelRecordPutDto putDto)
        {
            var recordEntity = this.orderCancelRecordData.Get(orderCancelRecordId).GetAwaiter().GetResult();
            if (recordEntity == null)
            {
                throw new ArgumentException("此订单取消记录不存在");
            }
            if (recordEntity.CancelStatus != OrderValidationStatus.Pending)
            {
                throw new ArgumentException("此订单取消记录已被审核完成，无需重复操作");
            }
            var entity = putDto.As<OrderCancelRecordEntity>();
            entity.OrderCancelRecordId = orderCancelRecordId;
            entity.OrderNo = recordEntity.OrderNo;
            entity.DriverId = recordEntity.DriverId;
            entity.AdminId = adminDto.AdminId;
            entity.AdminFullName = adminDto.FullName;
            if (recordEntity.DriverId.HasValue)
            {
                this.pushMessageSendService.PushMessageForOrder(recordEntity.OrderId, PushMessageType.DriverCancelFailed);
            }
            return this.orderCancelRecordData.ValidationFail(entity).GetAwaiter().GetResult().As<OrderCancelRecordDto>();
        }

        public OrderCancelRecordDto ValidationSuccess(AdminDto adminDto, long orderCancelRecordId, OrderCancelRecordPutDto putDto)
        {
            var recordEntity = this.orderCancelRecordData.Get(orderCancelRecordId).GetAwaiter().GetResult();
            if (recordEntity == null)
            {
                throw new ArgumentException("此订单取消记录不存在");
            }
            if (recordEntity.CancelStatus != OrderValidationStatus.Pending)
            {
                throw new ArgumentException("此订单取消记录已被审核完成，无需重复操作");
            }
            var entity = putDto.As<OrderCancelRecordEntity>();
            entity.OrderCancelRecordId = orderCancelRecordId;
            entity.OrderNo = recordEntity.OrderNo;
            entity.DriverId = recordEntity.DriverId;
            entity.AdminId = adminDto.AdminId;
            entity.AdminFullName = adminDto.FullName;
            var orderDto = this.orderData.GetEntity(recordEntity.OrderId).GetAwaiter().GetResult();

            var orderPoolEntity = this.orderPoolData.Get(recordEntity.OrderId).GetAwaiter().GetResult();
            if (recordEntity.DriverId.HasValue)
            {
                orderDto.CloseOrderContent = recordEntity.CancelOrderPromising;
                if (!this.orderData.CancelOrder(orderDto).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("订单取消审核失败!");
                }
                if (!this.orderPoolData.ClearOrderAssign(recordEntity.OrderId).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("取消订单审核时，还原订单指派信息失败!");
                }
                if (!this.orderData.UpdateOrderStatusPlaceOrder(recordEntity.OrderId).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("取消订单审核时，还原订单状态信息失败!");
                }
                if(!this.orderData.UpdateOrderAdmountSettleResult(recordEntity.OrderId, OrderAmountSettleResultType.ReturnSameWay).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("修改订单金额原路退回失败!");
                }

                //UpdateTransportOrderStatusForCancleOrder(orderDto);
                //司机取消订单审核通过增加通知给用户
                this.notificationMessageRecordData.InsertAsync(new NotificationMessageRecordEntity()
                {
                    NotificationTitle = string.Format("司机取消订单审核通过，司机姓名：{0},车牌号：{1},订单编号：{2}", recordEntity.DriverName, recordEntity.VehicleNo, recordEntity.OrderNo),
                    NotificationType = NotificationMessageRecordType.DriverCancelOrder.ToString(),
                    CreateTime = DateTime.Now,
                    RelatedRecordId = orderDto.OrderId,
                    IsRead = false,
                    IsHandled = false,
                    UserId = orderDto.UserId
                }).GetAwaiter().GetResult();
                this.pushMessageSendService.PushMessageForOrder(orderDto.OrderId, PushMessageType.DriverCancel);
                var driver = this.driverData.GetDriverByIdAsync(recordEntity.DriverId.Value).Result;
                if (driver != null)
                {
                    this.pushMessageSendService.PushMessageForDriverAppVehicleCancelPassed(driver.UserId, orderDto.OrderNo, PushMessageType.DriverCancelPassed);
                }
            }
            else
            {
                orderDto.CloseOrderContent = recordEntity.CancelOrderPromising;
                if (!this.orderData.CancelOrder(orderDto).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("订单取消审核失败!");
                }
                if (!this.orderPoolData.UpdateStatusDone(orderDto.OrderId, null).GetAwaiter().GetResult())
                {
                    throw new ArgumentException("订单取消审核失败!");
                }
                this.redisClearService.RemoveOrderCatch(orderDto.OrderId, orderDto.OrderNo);

                //if (orderDto.DriverId.HasValue)
                //{
                //    UpdateTransportOrderStatusForCancleOrder(orderDto);
                //}
                //else
                //{
                //    var vehicleTransportRecord = this.vehicleTransportRecordData.Get(recordEntity.VehicleId, orderDto.OrderNo).GetAwaiter().GetResult();
                //    if (vehicleTransportRecord != null)
                //    {
                //        this.vehicleTransportRecordData.SetBatchIgnore(vehicleTransportRecord.VehicleTransportBatchId).GetAwaiter().GetResult();
                //        var vehicleCheckResult = this.vehicleTransportRecordData.CheckOrderNotCanceledExists(vehicleTransportRecord.VehicleTransportBatchNo).GetAwaiter().GetResult();
                //        if (vehicleCheckResult == 0)
                //        {
                //            this.vehicleTransportRecordData.UpdateVehicleTransportStatus(vehicleTransportRecord.VehicleTransportRecordId, TransportStatus.Cancel).GetAwaiter().GetResult();
                //            this.vehicleTransportRecordData.UpdateRollbackVehicleTransportCompleteRecordIsLatest(vehicleTransportRecord.VehicleId).GetAwaiter().GetResult();
                //        }
                //    }
                //}
                this.pushMessageSendService.PushMessageForOrder(orderDto.OrderId, PushMessageType.UserCancel);
            }
            //更新订单扩展信息装货照片信息为空  
            this.orderExtentionData.UpdateClearLoadPhotosByOrderNoAsync(orderDto.OrderNo).GetAwaiter().GetResult();
            this.redisClearService.RemoveOrderCatch(orderDto.OrderId, orderDto.OrderNo);

            return this.orderCancelRecordData.ValidationSuccess(entity).GetAwaiter().GetResult().As<OrderCancelRecordDto>();
        }
        ///// <summary>
        ///// 用户取消订单更新运输批次状态
        ///// </summary>
        ///// <param name="orderDto">订单信息</param>
        //private void UpdateTransportOrderStatusForCancleOrder(OrderEntity orderDto)
        //{
        //    if (orderDto.VehicleId.HasValue)
        //    {
        //        var vehicleTransportRecord = this.vehicleTransportRecordData.Get(orderDto.VehicleId.Value, orderDto.OrderNo).GetAwaiter().GetResult();
        //        if (vehicleTransportRecord != null)
        //        {
        //            this.vehicleTransportRecordData.SetBatchIgnore(vehicleTransportRecord.VehicleTransportBatchId).GetAwaiter().GetResult();
        //            var vehicleCheckResult = this.vehicleTransportRecordData.CheckOrderNotCanceledExists(vehicleTransportRecord.VehicleTransportBatchNo).GetAwaiter().GetResult();
        //            if (vehicleCheckResult == 0)
        //            {
        //                this.vehicleTransportRecordData.UpdateVehicleTransportStatus(vehicleTransportRecord.VehicleTransportRecordId, TransportStatus.Cancel).GetAwaiter().GetResult();
        //                this.vehicleTransportRecordData.UpdateRollbackVehicleTransportCompleteRecordIsLatest(vehicleTransportRecord.VehicleId).GetAwaiter().GetResult();
        //            }
        //        }
        //    }
        //}
    }
}
